#include "qLSearchwidget.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QDesktopWidget>
#include <QScrollBar>




QLSearchWidget::QLSearchWidget(QWidget *parent)
	: QMyBaseFormWidget(parent)
    ,m_selectedText("") 
    ,m_selectedTextName("")
    ,m_chc(0)
    ,pItemDelegate(0)
    ,editorOpen(false)
{
	ui.setupUi(this);
    m_chc = new CHelperClass(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
    ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));
    connect(ui.tableView_2 ,SIGNAL(doubleClicked (const QModelIndex & )),this ,SLOT(slotDoubleMC(const QModelIndex &)));

    ui.tableView_2->setItemDelegate(&pItemDelegate);
    connect(this ,SIGNAL(editCell()),this ,SLOT(openEditor()));
    connect(this ,SIGNAL(closeCell()),this, SLOT(closeEditor()));
    ui.tableView_2->verticalScrollBar()->setMaximumHeight(10000);
    lista("%");

}

QLSearchWidget::~QLSearchWidget()
{
    delete m_chc;
    m_chc = 0;

}

void QLSearchWidget::radioButtonClicked()
{
    lista(ui.lineEdit->text());
}

void QLSearchWidget::pressEscape()
{
    emit closeW();
}


void QLSearchWidget::lista(const QString& nameSearch)
{
    if (nameSearch.length() < 0)
    {
        ui.tableView->hide();
        return;
    }
    if (nameSearch.length() < 2)
    {
        return;
    }

    bool isNumeric = false;
    nameSearch.toInt(&isNumeric); 

    int r = 0;
    int c = 3;
    int fieldNo[3];
    QString country[3];
    int colWidth[] = {40, 450, 150};
    QString colName[] = {"id_proizvod", "artikal", "edm"};
    QString temp = "";
        if (isNumeric)
        {
            temp = "SELECT id_proizvod, artikal, edm, firma_id "
            "FROM proizvodi_sostav "
            "LEFT JOIN artikli ON proizvodi_sostav.id_proizvod = artikli.id "
            "WHERE proizvodi_sostav.id_proizvod = "+ nameSearch +" "
            "GROUP BY id_proizvod limit 1000";
        }
        else
        {
            temp = "SELECT id_proizvod, artikal, edm, firma_id "
            "FROM proizvodi_sostav "
            "LEFT JOIN artikli ON proizvodi_sostav.id_proizvod = artikli.id "
            "WHERE artikal like '%"+ nameSearch +"%'"
            "GROUP BY id_proizvod limit 1000";
        }

    QSqlQuery query(temp);
    model = new QStandardItemModel(r,c);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Шифра"));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Артикал"));
    model->setHeaderData( 2, Qt::Horizontal, trUtf8("Едм"));

    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
    header->setClickable(true);
    ui.tableView->setHorizontalHeader(header);
    header->show();
    m_chc->createSaldoMap(0);
    int row = 0;
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            fieldNo[i] = query.record().indexOf(colName[i]);
            QStandardItem *item = new QStandardItem(query.value(fieldNo[i]).toString());
            item->setEditable(false);
            ui.tableView->setRowHeight(row, 18);
            ui.tableView->setColumnWidth(i, colWidth[i]);
            model->setItem(row, i, item);
        }
        row++;
    } 
    QItemSelectionModel *sm = ui.tableView->selectionModel();
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
        this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
    ui.tableView->show();
}

void QLSearchWidget::on_lineEdit_textChanged(const QString &)
{
	lista(ui.lineEdit->text());
}

void QLSearchWidget::on_lineEdit_2_textChanged(const QString &)
{
    lista(ui.lineEdit->text());
}

void QLSearchWidget::on_tableView_clicked(const QModelIndex &modelX)
{
	int i = modelX.row();
	m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
}

void QLSearchWidget::setFocusSearchField()
{
	ui.lineEdit->setFocus();
}


void QLSearchWidget::pressReturn()
{
    if (ui.lineEdit->hasFocus())
    {
        ui.tableView->setFocus();
    }
    else if (ui.tableView->hasFocus())
	{
		QString magTip = "0";
        emit sLSearchToDokument(m_selectedText, m_selectedTextName, m_selectedTextNameSaldo, magTip);	
	}
    else if (ui.tableView_2->hasFocus())
    {
        if (editorOpen)
        {
            emit closeCell();
        }
        else
        {
            emit editCell();
        }
        editorOpen = !editorOpen;
    }
}

void QLSearchWidget::setInitText(QString text)
{
	ui.lineEdit->setText(text);
	ui.lineEdit->selectAll();
	ui.lineEdit->setFocus();
}

void QLSearchWidget::selectionChanged(QModelIndex modelX, QModelIndex modelY)
{
    int i = modelX.row();
    m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
    m_selectedText_name = model->item(i, 1) ? model->item(i, 1)->text():"";
    lista_detail(m_selectedText);
}

void QLSearchWidget::lista_detail(const QString& nameSearch)
{
    bool ok1;
    float kolMusterija = ui.lineEdit_2->text().toFloat(&ok1);
    pItemDelegate.setKolicinaMusterija(kolMusterija);
    QLocale loc;
    if (nameSearch.length() < 0)
    {
        ui.tableView_2->hide();
        return;
    }

    int r = 0;
    int c = 7;
    int fieldNo[7];
    QString country[7];
    int colWidth[] = {0, 40, 250, 70, 80, 250, 40};
    QString colName[] = {"id", "sifra", "artikal", "edm", "kolicina", "", ""};
    QString temp = 
        "SELECT artikli.id, artikli.sifra, artikli.artikal, artikli.edm, proizvodi_sostav.kolicina, proizvodi_sostav.firma_id, artikli.kategorija "
        "FROM proizvodi_sostav "
        "LEFT JOIN artikli ON proizvodi_sostav.id_artikal = artikli.id  "
        "WHERE proizvodi_sostav.id_proizvod =";
    temp += m_selectedText;
    temp += "";
    QSqlQuery query(temp);

    model2 = new QStandardItemModel(r,c);
    model2->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
    model2->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
    model2->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
    model2->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм."));
    model2->setHeaderData( 4, Qt::Horizontal, trUtf8("Количина"));
    model2->setHeaderData( 5, Qt::Horizontal, trUtf8("Количина во магацин на артикли"));
    model2->setHeaderData( 6, Qt::Horizontal, trUtf8("Инфо"));
    

    ui.tableView_2->setModel(model2);
    header2 = new QHeaderView(Qt::Horizontal, this);
    header2->setClickable(true);
    ui.tableView_2->setHorizontalHeader(header2);
    header2->show();
    int row = 0;
   
    while (query.next()) 
    {
        float saldo = 0; 
        float kolvk = 0;
        QBrush newBrush;

        if (query.value(5).toInt() == 1)
        {
            newBrush.setColor(Qt::darkRed);
        }
        else
        {
            newBrush.setColor(Qt::black);
        }

        for (int i = 0; i < c; i++)
        {
            fieldNo[i] = query.record().indexOf(colName[i]);
            //             QStandardItem *item = new QStandardItem(query.value(fieldNo[i]).toString());
            QStandardItem *item = NULL;
            QString temp = query.value(fieldNo[i]).toString();

            if ((i > 3) && (i < 5))
            {
                kolvk = temp.toFloat();
                kolvk = kolvk * kolMusterija;
                temp =  loc.toString(kolvk, 'f', 2);
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignRight);

            }
            else if (i == 2)
            {
                item = new QStandardItem(temp);
                if (query.value(6).toInt())
                {
                    QIcon ic1(":/sterna/Resources/arrow-down-icon.png");
                    item->setIcon(ic1);   
                }
            }

            else if (i == 5)
            {
                saldo = m_chc->getLagerLista(query.value(0).toString() , (QString)"ART_PRILIV") - 
                m_chc->getLagerLista(query.value(0).toString() , (QString)"ART_ODLIV"); 
                temp =  loc.toString(saldo, 'f', 2);
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignRight);
            }
            else if ((i == 6))
            {
                temp = "";
                item = new QStandardItem(temp);
                if (saldo >= kolvk)
                {
                    QIcon ic1(":/sterna/Resources/ok.png");
                    item->setIcon(ic1);
                }
                else
                {
                    QIcon ic1(":/sterna/Resources/stop.png");
                    item->setIcon(ic1);
                }
                
                //item->setToolTip(trUtf8("Платена Фактура"));
            }
            else
            {
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignLeft);
            }
            item->setForeground(newBrush);
            item->setEditable(false);
            ui.tableView_2->setRowHeight(row, 18);
            ui.tableView_2->setColumnWidth(i, colWidth[i]);
            model2->setItem(row, i, item);
        }
        row++;
    } 
    QItemSelectionModel *sm = ui.tableView_2->selectionModel();
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
        this, SLOT(selectionChangedDetail(QModelIndex,QModelIndex)));
    ui.tableView_2->show();
}

void QLSearchWidget::selectionChangedDetail(QModelIndex modelX, QModelIndex modelY )
{
    closeEditor();
}

void QLSearchWidget::openEditor()
{
    //	tableView->closePersistentEditor(indexPrev);

    QModelIndexList indexes = ui.tableView_2->selectionModel()->selection().indexes();
    index = indexes.at(0);	// To get the row/column numbers use 
    if (index.column() > 1)
    {
        ui.tableView_2->openPersistentEditor(index);
    }

}

void QLSearchWidget::closeEditor()
{
    ui.tableView_2->closePersistentEditor(index);
    editorOpen = false;
}

void QLSearchWidget::slotDoubleMC(const QModelIndex & ind)
{
    if (editorOpen)
    {
        emit closeCell();
    }
    else
    {
        emit editCell();
    }
    editorOpen = !editorOpen;
}